import React, { useEffect, useState } from "react";
import { Table, Button, Modal ,Tree } from "antd";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import axios from "axios";

const RoleList = () => {
  const [dataSource, setDataSource] = useState([]);
  const [treeData, setTreeData] = useState([]);
  const [currntKeys, setCurrntKeys] = useState([]);
  
  const [isModalVisible, setIsModalVisible] = useState(false);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      render: (id) => <b>{id}</b>,
    },
    {
      title: "角色名称",
      dataIndex: "roleName",
    },

    {
      title: "操作",
      render: (item) => (
        <div>
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            style={{ marginRight: "20px" }}
            onClick={() => {
                setCurrntKeys(item.rights)
                handleCancel(true)
            }}
          />

          <Button
            type="primary"
            shape="circle"
            icon={<DeleteOutlined />}
            danger
          />
        </div>
      ),
    },
  ];

  const handleCancel = (show) => {
    setIsModalVisible(show);
  };

  const onCheck = (e) => {
    setCurrntKeys(e.checked)
  };

  const onOk = () => {
    console.log(currntKeys)
    // handleCancel(false)
  }
  useEffect(() => {
    axios.get("http://localhost:9925/roles").then((res) => {
      setDataSource(res.data);
    });
  }, []);
  useEffect(() => {
    axios.get("http://localhost:9925/rights?_embed=children").then((res) => {
      setTreeData(res.data);
    });
  }, []);

  return (
    <>
      <Table
        rowKey="id"
        dataSource={dataSource}
        columns={columns}
        pagination={{ pageSize: 5 }}
      />
      <Modal
        title="Basic Modal"
        visible={isModalVisible}
        onOk={onOk}
        onCancel={() => handleCancel(false)}
      >
        <Tree
          checkable
          checkStrictly={true}
          checkedKeys={currntKeys}
          onCheck={onCheck}
          treeData={treeData}
        />
      </Modal>
    </>
  );
};

export default RoleList;
